import './main.scss'
import { useState, useEffect, useRef } from 'react'
import SvgIcon from '@/components/SvgIcon'
import { Tooltip, Avatar, Tag, message, Modal, Button } from 'antd'
import { UserActions } from '@/store'
import { useDispatch, useSelector } from 'react-redux'
import { Outlet, useNavigate, useLocation } from 'react-router-dom'
import { createWebSocket, userSign } from '@/api/signIn'
import { baseURL } from '@/setting'

function Main() {
  const dispatch: any = useDispatch()
  const [lock, setLock] = useState(false)
  const [current, setCurrent] = useState(50)
  const [store, setStore] = useState(50)
  const [hide, setHide] = useState(false)
  const [link, setLink] = useState<any>([0])
  const [select, setSelect] = useState(0)
  const [toggle, setToggle] = useState(true)
  const [userStatus, setUserStatus] = useState(false)
  const storeUserInfo = useSelector((state: any) => state.user.userInfo)
  const token = useSelector((state: any) => state.user.token)
  const [userInfo, setUserInfo] = useState(storeUserInfo)
  const [fullScreen, setFullScreen] = useState(false)
  const maskTop = [50, 150, 250, 350, 450]
  const [modal, contextHolder] = Modal.useModal()
  const [signInData, setSignInData] = useState<any>({})
  const [isModalOpen, setIsModalOpen] = useState(false)

  // 创建WebSocket连接
  const wsRef = useRef<any>(null)

  // 使用 useNavigate 钩子进行路由跳转
  const navigate = useNavigate()
  const location = useLocation()

  // 学生签到
  const toUserSign = async () => {
    const res: any = await userSign({ id: signInData.id })
    if (res.code === 200) {
      message.success('签到成功！')
    }
  }

  // 初始化的时候进行数据找回
  useEffect(() => {
    wsRef.current = createWebSocket(token)
    // 打开WebSocket连接
    wsRef.current.onopen = () => {
      console.log('WebSocket连接已打开')
    }

    // 监听WebSocket消息
    wsRef.current.onmessage = (event: any) => {
      // 尝试解析JSON数据
      const jsonMatch = event.data.match(/({.*})/s)

      if (jsonMatch && jsonMatch[1]) {
        const jsonString = jsonMatch[1]
        try {
          const data = JSON.parse(jsonString)
          // 根据解析后的数据执行业务逻辑
          if (data.id) {
            // 在这里添加处理业务逻辑的代码
            setSignInData(data)
          }
          if (data.type === 1) {
            setSignInData({ context: data.content, id: data.user.id })
          }
        } catch (error) {
          // 如果解析出错，输出错误信息
          console.error('数据解析错误:', error)
        }
      } else {
        console.error('未找到有效的 JSON 对象')
      }
    }

    // 监听WebSocket错误
    wsRef.current.onerror = (error: any) => {
      console.error('WebSocket发生错误:', error)
    }

    // 监听WebSocket关闭
    wsRef.current.onclose = () => {
      console.log('WebSocket连接已关闭')
    }

    switch (location.pathname) {
      case '/main/iFlytek':
        setCurrent(maskTop[0])
        setStore(maskTop[0])
        setLink([0])
        setSelect(0)
        break
      case '/main/class':
        setCurrent(maskTop[1])
        setStore(maskTop[1])
        setLink([0, 1])
        setSelect(1)
        break
      case '/main/text':
        setCurrent(maskTop[2])
        setStore(maskTop[2])
        setLink([0, 2])
        setSelect(2)
        break
      case '/main/face':
        setCurrent(maskTop[3])
        setStore(maskTop[3])
        setLink([0, 3])
        setSelect(3)
        break
      case '/main/user':
        setCurrent(maskTop[4])
        setStore(maskTop[4])
        setLink([0, 4])
        setSelect(4)
        break
    }

    return () => {
      wsRef.current.close()
    }
  }, [])

  window.onbeforeunload = () => {
    wsRef.current.close()
  }

  useEffect(() => {
    if (Object.keys(signInData).length > 0) {
      modal.confirm(config)
    }
  }, [signInData])

  const config = {
    title: <div style={{ fontSize: '18px' }}>{signInData.context}</div>,
    okText: '参与签到',
    async onOk() {
      await toUserSign()
    },
  }

  // 获取账号状态
  const getUserStatus = () => {
    if (userInfo.birthday && userInfo.phone) {
      setUserStatus(true)
    }
  }

  useEffect(() => {
    setUserInfo(storeUserInfo)
  }, [storeUserInfo])

  useEffect(() => {
    getUserStatus()
  }, [userStatus])

  // 侧边栏锁定
  const handleChangeLock = () => {
    setLock(!lock)
  }

  // 鼠标点击触发路由跳转
  const handleClick = async (num: number) => {
    setToggle(false)
    setCurrent(maskTop[num])
    setStore(current)
    setSelect(num)
    !link.includes(num) && setLink([...link, num])
    await new Promise((resolve) => setTimeout(resolve, 100))
    setToggle(true)

    switch (num) {
      case 0:
        navigate('/main/iFlytek')
        break
      case 1:
        navigate('/main/class')
        break
      case 2:
        navigate('/main/text')
        break
      case 3:
        navigate('/main/face')
        break
      case 4:
        navigate('/main/user')
        break
    }
  }

  // 鼠标移入整体事件
  const handlemouseOver = (num: number) => {
    setCurrent(maskTop[num])
  }

  // 鼠标移出整体事件
  const handlemouseOut = () => {
    setCurrent(store)
  }

  // 鼠标移入展示侧边栏
  const handlemouseEnter = () => {
    !lock && setHide(false)
  }

  // 鼠标移出展示侧边栏
  const handlemouseLeave = () => {
    !lock && setHide(true)
  }

  // 关闭标签的触发事件
  const handleColse = (index: number) => {
    if (link.length !== 1) {
      setLink((currentLink: any) => {
        const newLink = [...currentLink]
        newLink.splice(index, 1)
        return newLink
      })
      handleClick(link[index - 1])
    }
  }

  // 侧边导航栏是否固定
  useEffect(() => {
    lock && setHide(false)
  }, [lock])

  return (
    <div className="Main">
      {contextHolder}
      <div
        onMouseEnter={handlemouseEnter}
        onMouseLeave={handlemouseLeave}
        className={`left ${hide ? 'changeLeft' : ''}`}
      >
        <div></div>
        <ul>
          <div className={`mask ${hide ? 'changemask' : ''}`} style={{ top: current }}>
            <div></div>
            <div></div>
            <div></div>
          </div>
          <Tooltip placement="right" color="#3fc1c9" title="学习引擎">
            <li
              className={`${hide ? 'changeli' : ''}`}
              onClick={() => handleClick(0)}
              onMouseOver={() => handlemouseOver(0)}
              onMouseOut={handlemouseOut}
            >
              <SvgIcon name="IFlytek" size="35" />
            </li>
          </Tooltip>
          <Tooltip placement="right" color="#3fc1c9" title="智能选课">
            <li
              className={`${hide ? 'changeli' : ''}`}
              onClick={() => handleClick(1)}
              onMouseOver={() => handlemouseOver(1)}
              onMouseOut={handlemouseOut}
            >
              <SvgIcon name="class" size="35" />
            </li>
          </Tooltip>
          <Tooltip placement="right" color="#3fc1c9" title="行政之路">
            <li
              className={`${hide ? 'changeli' : ''}`}
              onClick={() => handleClick(2)}
              onMouseOver={() => handlemouseOver(2)}
              onMouseOut={handlemouseOut}
            >
              <SvgIcon name="correction" size="35" />
            </li>
          </Tooltip>
          <Tooltip placement="right" color="#3fc1c9" title="面试模拟">
            <li
              className={`${hide ? 'changeli' : ''}`}
              onClick={() => handleClick(3)}
              onMouseOver={() => handlemouseOver(3)}
              onMouseOut={handlemouseOut}
            >
              <SvgIcon name="recognition" size="35" />
            </li>
          </Tooltip>
          <Tooltip placement="right" color="#3fc1c9" title="个人信息">
            <li
              className={`${hide ? 'changeli' : ''}`}
              onClick={() => handleClick(4)}
              onMouseOver={() => handlemouseOver(4)}
              onMouseOut={handlemouseOut}
            >
              <SvgIcon name="userInfo" size="35" />
            </li>
          </Tooltip>
        </ul>
      </div>
      <div className="right">
        <div className="rtop">
          <div className="rtopLeft">
            <img
              onClick={() => {
                navigate('/')
              }}
              className="rtoplImg"
              src="/assets/images/font.png"
              alt=""
            />
            <div onClick={handleChangeLock} className="unfoldSvg">
              {lock ? (
                <SvgIcon name="lockclose" size="28" />
              ) : (
                <SvgIcon name="lockopen" size="28" />
              )}
            </div>
            <div className="rtoplWhere">当前位置</div>
          </div>
          <div className="rtopright">
            <Tooltip placement="bottom" title="微信小程序端">
              <div
                onClick={() => {
                  setIsModalOpen(true)
                }}
              >
                <SvgIcon name="wechat2" size="28" />
              </div>
            </Tooltip>
            <Tooltip placement="bottom" title="刷新">
              <div
                onClick={() => {
                  window.location.reload()
                }}
              >
                <SvgIcon name="refresh" size="28" />
              </div>
            </Tooltip>
            <Tooltip placement="bottom" title={!fullScreen ? '全屏' : '退出全屏'}>
              <div
                onClick={() => {
                  setFullScreen(!fullScreen)
                  if (!fullScreen) {
                    document.body.requestFullscreen()
                  } else {
                    document.exitFullscreen()
                  }
                }}
              >
                <SvgIcon name={!fullScreen ? 'full' : 'exitFull'} size="28" />
              </div>
            </Tooltip>
            <Tooltip placement="bottom" title={`状态：${!userStatus ? '未实名' : '实名'}`}>
              <div>
                <Avatar
                  size={46}
                  style={{ backgroundColor: '#ccc' }}
                  src={
                    <img
                      src={
                        userInfo.image
                          ? `${baseURL}/img/${userInfo.image}`
                          : '/assets/images/avatar.png'
                      }
                      alt="avatar"
                    />
                  }
                />
                <span style={{ marginLeft: '10px', fontWeight: '600', color: '#222' }}>
                  {userInfo.username}
                </span>
              </div>
            </Tooltip>
            <Tooltip placement="bottom" title="退出登录">
              <div
                onClick={() => {
                  localStorage.setItem('token', JSON.stringify(''))
                  dispatch(UserActions.changeToken(''))
                  navigate('/')
                  message.success('退出成功！')
                }}
              >
                <SvgIcon name="quit" size="28" />
              </div>
            </Tooltip>
          </div>
        </div>
        <div className="rtop2">
          {link.map((num: number, index: number) => {
            let tagText

            switch (num) {
              case 0:
                tagText = '学习引擎'
                break
              case 1:
                tagText = '智能选课'
                break
              case 2:
                tagText = '行政之路'
                break
              case 3:
                tagText = '面试模拟'
                break
              case 4:
                tagText = '个人信息'
                break
            }
            return (
              <Tag
                color={select === num ? '#3fc1c9' : '#ccc'}
                className="rtop2Tag"
                key={num}
                style={{ cursor: 'pointer' }}
                closable={num === 0 ? false : true}
                onClose={() => handleColse(index)}
                onClick={() => handleClick(num)}
              >
                {tagText}
              </Tag>
            )
          })}
        </div>
        <div className={`rcontent ${toggle ? 'zoomIn' : ''}`}>
          <Outlet />
        </div>
      </div>
      <Modal
        title="微信小程序二维码"
        footer={
          <Button
            type="primary"
            onClick={() => {
              setIsModalOpen(false)
            }}
          >
            确定
          </Button>
        }
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false)
        }}
      >
        <img src="/assets/images/wechat.jpg" alt="" />
      </Modal>
    </div>
  )
}

export default Main
